package cn.mengfly.testnrz.netty.protobuf;

import cn.mengfly.testnrz.netty.NettyEchoClient;
import cn.mengfly.testnrz.nio.NioDemoConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

public class NettyDumpSendClient {

    Bootstrap b = new Bootstrap();

    public void runClient() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(NioDemoConfig.SOCKET_IP, NioDemoConfig.SOCKET_PORT);
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline().addLast(NettyEchoClient.NettyEchoClientHandler.INSTANCE);
                }
            });
            ChannelFuture f = b.connect();
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) {
                    if (channelFuture.isSuccess()) {
                        System.out.println("EchoClient 客户端连接成功");
                    } else {
                        System.out.println("EchoClient 客户端连接失败");
                    }
                }
            });
            f.sync();
            Channel channel = f.channel();
            String content = "这是一条测试数据";
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
            for (int i = 0; i < 1000; i++) {
                ByteBuf buf = channel.alloc().buffer();
                buf.writeBytes(bytes);
                channel.writeAndFlush(buf);
            }
            ChannelFuture closeFuture = f.channel().closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new NettyDumpSendClient().runClient();
    }
}
